<script setup lang="ts">
import { ref } from 'vue';

// 图片src状态
const chartImage = ref('');
// 加载状态
const isLoading = ref(false);
// 错误信息
const errorMessage = ref('');

// 获取echarts图片的函数
const fetchChartImage = async () => {
  isLoading.value = true;
  errorMessage.value = '';
  
  try {
    const response = await fetch('http://localhost:8080/api/chart/pie');
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    
    const data = await response.json();
    
    if (data.success) {
      chartImage.value = data.imageSrc;
    } else {
      throw new Error(data.message || '获取图表失败');
    }
  } catch (error) {
    console.error('获取图表失败:', error);
    errorMessage.value = error instanceof Error ? error.message : '未知错误';
  } finally {
    isLoading.value = false;
  }
};
</script>

<template>
  <div class="app-container">
    <h1>ECharts 图表示例</h1>
    
    <div class="button-container">
      <button 
        @click="fetchChartImage" 
        :disabled="isLoading"
        class="fetch-button"
      >
        {{ isLoading ? '加载中...' : '获取图表' }}
      </button>
    </div>
    
    <div class="chart-container">
      <!-- 显示错误信息 -->
      <div v-if="errorMessage" class="error-message">
        {{ errorMessage }}
      </div>
      
      <!-- 显示加载状态 -->
      <div v-else-if="isLoading" class="loading-message">
        正在获取图表数据...
      </div>
      
      <!-- 显示图表图片 -->
      <img 
        v-else-if="chartImage" 
        src="" 
        alt="ECharts 饼图" 
        class="chart-image"
      />
      
      <!-- 初始提示信息 -->
      <div v-else class="initial-message">
        点击上方按钮获取图表
      </div>
    </div>
  </div>
</template>

<style scoped>
.app-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}

h1 {
  text-align: center;
  color: #333;
  margin-bottom: 30px;
}

.button-container {
  text-align: center;
  margin-bottom: 30px;
}

.fetch-button {
  background-color: #1890ff;
  color: white;
  border: none;
  padding: 10px 24px;
  font-size: 16px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.fetch-button:hover:not(:disabled) {
  background-color: #40a9ff;
}

.fetch-button:disabled {
  background-color: #d9d9d9;
  cursor: not-allowed;
}

.chart-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
  background-color: #f5f5f5;
  border-radius: 8px;
  padding: 20px;
}

.chart-image {
  max-width: 100%;
  max-height: 400px;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

.error-message {
  color: #f5222d;
  text-align: center;
}

.loading-message,
.initial-message {
  color: #666;
  text-align: center;
}
</style>
